<template>
  <div>
    <!-- 添加或修改公告对话框 -->
    <el-dialog :title="title" :visible.sync="$parent.openadd" width="780px" append-to-body>
      <div class="center_dialog">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-divider>变卖设备</el-divider>
          <el-form-item label="变卖设备" prop="equipmentAccountIds">
            <el-select v-model="form.equipmentAccountIds" multiple placeholder="请选择变卖设备" style="width:100%">
              <el-option v-for="dict in basedata" :key="dict.index"
                :label="`${dict.equipmentName}(${dict.equipmentNum})`" :value="dict.equipmentAccountId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-divider>申请信息</el-divider>
          <el-form-item label="申请部门" prop="appliedDeptId">
            <el-select v-model="form.appliedDeptId" @change="systemChange(form.appliedDeptId, 1)" placeholder="请选择申请部门"
              style="width:100%">
              <el-option v-for="dict in systemdict" :key="dict.index" :label="dict.deptName" :value="dict.deptId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="申请人" prop="applicantId">
            <el-select v-model="form.applicantId" placeholder="请选择申请人" style="width:100%">
              <el-option v-for="dict in userData" :key="dict.value" :label="dict.userName" :value="dict.userId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="申请原因" prop="reason">
            <el-input type="textarea" v-model="form.reason" placeholder="请输入申请原因" />
          </el-form-item>
          <!-- <el-form-item label="设备图片" prop="image">
            <Upload :imgUrl="form.image" @clearimgUrl="() => form.image = ''" @handleSuccess="handleSuccess"></Upload>
          </el-form-item> -->
          <el-form-item label="设备附件" prop="file">
            <!-- <el-upload :action="action_url" list-type="text" accept=".pdf,.docx,,.doc,.xls,.xlsx,.jpg,'.png'"
              :headers="header_url" :show-file-list="true" :on-success="handlePictureCardflie"
              :before-upload="beforeAvatarUploadflie" :on-remove="handleremoveflie" :limit="1">
              <el-button size="medium" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                上传附件支持xls,xlsx,docx,doc,pdf,jpg,png格式,大小不超过50M。
              </div>
            </el-upload> -->
            <FileUpload v-model="form.file" :limit="1" :fileSize="50"
              :fileType="['xls', 'xlsx', 'doc', 'docx', 'pdf', 'jpg', 'png']">
            </FileUpload>
          </el-form-item>
          <el-divider>审核信息</el-divider>
          <el-form-item label="审核人" prop="auditVosUser">
            <el-select v-model="form.auditVosUser" collapse-tags multiple placeholder="请选择审核人" style="width:100%">
              <el-option v-for="dict in allUserData" :key="dict.index" :label="dict.userName" :value="dict.userId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="">
            <span v-for="(tag, index) in tagUserList" :key="index">
              <el-tag closable disable-transitions @close="tagChange(tag, index)">
                <span>{{ tag.name }}</span>
              </el-tag>
              <span style="font-size:28px;position: relative;top: 5px;">
                <template v-if="index !== tagUserList.length - 1">
                  <i class="el-icon-caret-right"></i>
                </template>
              </span>
            </span>

          </el-form-item>
          <el-form-item label="抄送人" prop="auditVosType">
            <el-select v-model="form.auditVosType" multiple placeholder="请选择抄送人" style="width:100%">
              <el-option v-for="dict in allUserData" :key="dict.index" :label="dict.userName" :value="dict.userId">
              </el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="内容">
              <editor v-model="form.noticeContent" :min-height="192"/>
            </el-form-item> -->
        </el-form>
      </div>
      <div align="center" slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="() => $parent.openadd = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getuserlist, getsystemlist } from '@/api/equipment/equipment.js'
import { postSale, postPartInfolist, getChlidrenSale } from '@/api/management/management.js'
import Upload from '@/components/upload/index.vue'
export default {
  props: ['title', 'rowObj'],
  components: {
    Upload
  },
  data () {
    return {
      form: {
        "equipmentAccountIds": [], //调拨设备
        "type": 6,//固定写死为6
        "appliedDeptId": undefined, //申请部门ID
        "applicantId": undefined, //申请人ID
        "reason": undefined, //调拨原因
        "file": undefined, //附件
        auditVosUser: [],//审核人
        auditVosType: [],//抄送人
        "auditVos": [] //审核信息（审核人在前，抄送人在后）
      },
      placeData: [],//位置列表
      userData: [],//负责人列表
      systemdict: [],//部门列表
      allUserData: [],//全部用户列表
      basedata: [],//设备基值列表
      rules: {
        equipmentAccountIds: { required: true, message: '必填', trigger: 'blur' },
        deptId: { required: true, message: '必填', trigger: 'blur' },
        placeId: { required: true, message: '必填', trigger: 'blur' },
        headId: { required: true, message: '必填', trigger: 'blur' },
        appliedDeptId: { required: true, message: '必填', trigger: 'blur' },
        applicantId: { required: true, message: '必填', trigger: 'blur' },
        meterageFlag: { required: true, message: '必填', trigger: 'blur' },
        reason: { required: true, message: '必填', trigger: 'blur' },
        file: { required: true, message: '必填', trigger: 'blur' },
        auditVosUser: { required: true, message: '必填', trigger: 'blur' },
        auditVosType: { required: false, message: '必填', trigger: 'blur' },
      }
    }
  },
  computed: {
    /**
     * 审核人
     */
    tagUserList () {
      let Arr = []
      this.form.auditVosUser.map(item => {
        this.allUserData.map(value => {
          if (item === value.userId) {
            Arr.push({
              userId: value.userId,
              name: value.userName
            })
          }
        })
      })
      return Arr
    },
  },
  created () {
    this.getlist()
  },
  methods: {
    handleSuccess (res) {
      console.log(res);
      this.form.image = res.res.data.url
    },
    async getlist () {
      let systemdata = await getsystemlist();//部门
      let userdata = await getuserlist();
      let basedata = await postPartInfolist({ 'params[userStatuses]': 3 });
      this.systemdict = systemdata.data
      this.allUserData = userdata.data
      this.basedata = basedata.data
      this.form.appliedDeptId = this.$store.state.user.deptId
      this.form.applicantId = this.$store.state.user.userId
      this.systemChange(this.form.appliedDeptId, 1, true)
      if (this.title === '申请变卖(重新申请)') {
        let { data: data } = await getChlidrenSale(this.rowObj.disposalId)
        this.form.equipmentAccountIds = data.disposalEquipmentAccountVos && data.disposalEquipmentAccountVos.map(item => item.eaPartInfoVo && item.eaPartInfoVo.equipmentAccountId)
        this.form.appliedDeptId = data.appliedDeptId
        this.form.applicantId = data.applicantId
        this.form.reason = data.reason
        this.form.file = data.file
        this.form.auditVosUser = data.auditVos.filter(item => {
          if (item.userType === '0') {
            return item.userId
          }
        })
        this.form.auditVosUser = this.form.auditVosUser.map(item => item.userId)
        this.form.auditVosType = data.auditVos.filter(item => {
          if (item.userType === '1') {
            return item.userId
          }
        })
        this.form.auditVosType = this.form.auditVosType.map(item => item.userId)
        this.systemChange(this.form.appliedDeptId, 1, true)
      }
    },
    tagChange (val, index) {
      console.log(val);
      this.form.auditVosUser.splice(index, 1)
    },
    //提交
    submitForm () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.title === '修改调拨') {//修改
            return this.$message.warning('暂无修改此功能')
            // let params = {
            //   ...this.form
            // }
            // putequipmentlist(params).then(res => {
            //   if (res.code === 200) {
            //     this.$message.success(res.msg)
            //     this.$parent.open = false
            //     this.$parent.getList()
            //   }
            // })
          } else {//新增
            // { "userId": 3, /*用户ID*/ "userType": "0" /*用户类型（0审核人）*/ },
            //将审核人与抄送人转换为接口需要的格式转换为接口需要的格式
            this.form.auditVos = this.form.auditVosUser.map(item => {//审核人
              return {
                userId: item,
                userType: '0'
              }
            });
            this.form.auditVosType.map(item => {//抄送人
              this.form.auditVos.push(
                {
                  userId: item,
                  userType: '1'
                }
              )
            });
            //接口参数
            let params = {
              ...this.form
            }
            postSale(params).then(res => {
              if (res.code === 200) {
                this.$message.success(res.msg)
                this.$emit('handleUpdate')
              }
            })
          }
        }
      });
    },
    /**
     * 选择部门时触发
     */
    systemChange (value, key, init) {
      let params = {
        deptId: value//部门ID
      }
      getuserlist(params).then(res => {//查询负责人
        this.userData = res.data
      })
      if (!init) {
        //0则调入，1则申请
        key === 0 ? this.form.headId = undefined : this.form.applicantId = undefined
      }

    },
    handleremoveflie () {
      // 附件删除时调用
      this.form.file = ''
      // for (const key in this.flie) {
      //   this.flie[key] = ''
      // }
    },
    beforeAvatarUploadflie (file) {
      // 附件
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      const whiteList = ['pdf', 'docx', 'doc', 'xlsx', 'xls', 'jpg', 'png']
      const isLt2M = file.size / 1024 / 1024 < 50
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$message({
          message: '上传附件支持xls,xlsx,docx,doc,pdf,jpg,png格式,大小不超过50M。',
          type: 'warning'
        })
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 50MB!')
        return false
      }
    },
    handlePictureCardflie (file) {
      // 附件成功
      // if (this.form.file !== '') {
      //   return this.$message.error('只可上传一份附件')
      // }
      console.log(file);
      this.form.file = file.data.url
    },
  }
}
</script>

<style lang="scss" scoped>
.center_dialog {
  // text-align: center;
  width: 50%;
  // padding: 0 10% 0 10%;
  box-sizing: border-box;
  margin: 0px auto;
}

.el-tag--medium {
  margin: 0px 3px;
}
</style>